<template>
  <div class="product">
    <!--编辑分类-->
    <div class="common-level-rail">
      <el-button
        size="small"
        type="primary"
        @click="editClick"
        icon="el-icon-plus"
        v-auth="'/product/category/edit'"
        v-if="open_edit==false"
        >编辑分类</el-button>
      <!-- 按钮 -->
      <div v-if="open_edit==true">
        <el-button size="small" @click="dialogFormVisible" icon="el-icon-close">取 消 编 辑</el-button>
        <el-button size="small" icon="el-icon-check" type="primary" @click="submit" :loading="loading">确 定 保 存</el-button>
      </div>
    </div>

    <!--内容-->
    <div class="product-content">
      <div class="table-wrap">
        <el-table
          size="small"
          :data="tableData"
          row-key="category_id"
          default-expand-all
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column label="分类名称">
            <template slot-scope="scope">
              <span style="font-size:16px" v-if="open_edit==false">{{ scope.row.key }}</span>
              <span style="font-size:16px" v-if="open_edit==true"><i class="el-icon-lock"/></span>
              <span class="parent_cl">{{ scope.row.name }}</span>
              <span class="parent_small" v-if="open_edit==true">(顶级分类位置锁定)</span>
            </template>
          </el-table-column>
          <el-table-column label="显示状态" width="240px">
            <template slot-scope="scope">
              <div class="product-info-big" v-if="open_edit==false">
                <strong v-if="scope.row.is_show==1" class="orange">显示</strong>
                <span v-if="scope.row.is_show==0" class="gray">隐藏</span>
              </div>
              <div class="product-info-big" v-if="open_edit==true">
                <el-switch
                  v-model="scope.row.is_show"
                  :active-value="1"
                  :inactive-value="0"
                  :handleBeforeChange="()=>isShowFunc(scope.row)"
                  active-color="#13ce66"
                  inactive-color="#cccccc"
                ></el-switch>
              </div>
            </template>
          </el-table-column>
          <el-table-column type="expand" width="1px">
            <template slot-scope="scope">
              <el-table
                size="small"
                :data="scope.row.child"
                row-key="category_id"
                default-expand-all
                style="width: 100%"
                :show-header="false"
                class="draggable-table"
              >
                <el-table-column label="分类名称">
                  <template slot-scope="scope">
                    <span class="parent_ctr_icon" style="font-size:14px"><i class="el-icon-more-outline"/></span>
                    <span class="parent_ctr">{{ scope.row.name }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="显示状态" width="241px">
                  <template slot-scope="scope">
                    <div class="product-info" v-if="open_edit==false">
                      <strong v-if="scope.row.is_show==1" class="orange">显示</strong>
                      <span v-if="scope.row.is_show==0" class="gray">隐藏</span>
                    </div>
                    <div class="product-info" v-if="open_edit==true">
                      <el-switch
                        v-model="scope.row.is_show"
                        :active-value="1"
                        :inactive-value="0"
                        :handleBeforeChange="()=>isShowFunc(scope.row)"
                        active-color="#13ce66"
                        inactive-color="#cccccc"
                      ></el-switch>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import ProductApi from "@/api/product.js";
import Sortable from 'sortablejs';
export default {
  components: {
    Sortable
  },
  data() {
    return {
      /*切换菜单*/
      activeName: "1",
      /*是否加载完成*/
      loading: true,
      /*列表数据*/
      tableData: [],
      /*一页多少条*/
      pageSize: 20,
      /*一共多少条数据*/
      totalDataNumber: 0,
      /*当前是第几页*/
      curPage: 1,
      /*是否打开添加弹窗*/
      open_add: false,
      /*是否打开编辑弹窗*/
      open_edit: false,
      /*是否打开审核弹窗*/
      open_audit: false,
      /*当前编辑的对象*/
      categoryModel: {
        catList: [],
        model: []
      },
      batchIds: [],
      Sortablelist: [],
    };
  },
  created() {
    /*获取列表*/
    this.getData();
  },
  methods: {
    
    // 表格行拖拽
    initDrag() {
      const el = document.querySelectorAll(".draggable-table .el-table__body-wrapper > table > tbody");
      const vm = this;

      el.forEach((item,index)=>{
        // console.log(item)
        let arr = vm.tableData[index].child;
        let oldary = vm.tableData[index].child;
        console.log(arr,'arrarr')
        this.Sortablelist[index] = Sortable.create(item, {
          disabled: false, // 拖拽是否可用
          ghostClass: 'sortable-ghost', //拖拽样式
          animation: 150, // 拖拽延时
          // draggable: ".el-table__row--level-1",
          onEnd: function (e) { // 拖拽结束时触发
            console.log(e)
            arr.splice(e.newIndex, 0, arr.splice(e.oldIndex, 1)[0]);   // 数据处理，获取最新的表格数据
            // vm.$nextTick(function () {
            //   oldary = arr;
            // })
            // console.log(arr)
            console.log(vm.tableData[index].child)
          },
        });
      })
    },

    distroyDray(){
      this.Sortablelist.forEach((item)=>{
        item.option("disabled", true);
      })
      this.Sortablelist = [];
    },
    hasImages(e) {
      if (e) {
        return e.file_path;
      } else {
        return "";
      }
    },
    /*获取列表*/
    getData() {
      let self = this;
      let Params = {};
      self.loading = true;
      ProductApi.catadminList(Params, true)
        .then(data => {
          self.loading = false;
          self.tableData = data.data.list;
          self.categoryModel.catList = self.tableData;
          self.category_count = data.data.category_count;
        })
        .catch(error => {
          self.loading = false;
        });
    },
    /*每页多少条*/
    handleSizeChange(val) {
      this.curPage = 1;
      this.pageSize = val;
      this.getTableList();
    },
    /*选择第几页*/
    handleCurrentChange(val) {
      let self = this;
      self.curPage = val;
      self.loading = true;
      self.getTableList();
    },

    /*打开编辑*/
    editClick() {
      this.categoryModel.model = JSON.parse(JSON.stringify(this.categoryModel.catList));
      console.log(this.categoryModel.model)
      this.open_edit = true;
      setTimeout(()=>{
        this.initDrag();
      },100)
    },

    /*关闭编辑*/
    dialogFormVisible() {
      let self = this;
      this.open_edit = false;
      this.distroyDray();
      let catList = JSON.parse(JSON.stringify(this.categoryModel.model));
      catList.forEach((item,index)=>{
        self.$set(self.categoryModel.catList,[index],item)
        item.child.forEach((citem,cindex)=>{
          self.$set(self.categoryModel.catList[index].child,[cindex],citem)
        })
      })
      console.log(this.categoryModel.catList)
    },

    submit(){
      let self = this;
      let msg = '确认调整完成吗？';
      self
        .$confirm(msg, '提示', {
          type: 'warning'
        })
        .then(() => {
          let Params = {};
          Params.form = []
          const catList = self.categoryModel.catList;
          catList.forEach((item,index)=>{
            Params.form.push({category_id:item.category_id,is_show:item.is_show,sort:item.sort});
          })
          catList.forEach((item,index)=>{
            // Params.form.push(citem);
            if(item.child&&item.child.length>0){
              item.child.forEach((citem,cindex)=>{
                Params.form.push(citem);
              })
            }
          })
          // Params.form = self.categoryModel.catList;
          self.loading = true;
          ProductApi.catadminEdit(Params, true)
            .then(data => {
              self.loading = false;
              self.open_edit = false;
              self.distroyDray();
              self.$message({
                message: '恭喜你，调整成功',
                type: 'success'
              });
              // self.tableData = data.data.list;
              // self.categoryModel.catList = self.tableData;
              // self.category_count = data.data.category_count;
            })
            .catch(error => {
              self.loading = false;
              self.dialogFormVisible();
            });
        }).catch((ex)=>{
          console.log('colse')
        });
    },
    /*是否显示开关*/
    isShowFunc(e) {
      console.log(e.is_show)
    },
  }
};
</script>

<style>
  .product-info-big{
    font-size: 15px;
    line-height: 40px;
  }
  .product-info{
  }
  .parent_cl{
    margin-left: 20px;
    font-size: 15px;
    font-weight: bold;
  }
  .parent_small{
    margin-left: 20px;
    font-size: 11px;
    line-height: 40px;
    color: #bababa;
  }
  .parent_ctr{
    margin-left: 20px;
    font-size: 13px;
  }
  .parent_ctr_icon {
    margin-left: 30px;
  }
  .el-icon-more-outline{
    transform: rotate(90deg);
  }
  .el-table__expanded-cell{
    padding:0 !important;
  }
</style>
